// 412
package org.hwadee.controller;

import com.github.pagehelper.PageHelper;
import cn.hutool.http.HtmlUtil;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.hwadee.entity.Category;
import org.hwadee.entity.Comment;
import org.hwadee.entity.Post;
import org.hwadee.entity.User;
import org.hwadee.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/post")
public class PostController {

    @Autowired
    private PostService postService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private UserService userService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private PageOptionsService pageOptionsService;

    /**
     * 帖子详情页显示
     *
     * @param postId 帖子ID
     * @return modelAndView
     */
    @RequestMapping(value = "/{postId}")
    public String getArticleDetailPage(@RequestParam(value = "page", defaultValue = "1") int page,
                                       @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
                                       @PathVariable("postId") Integer postId, Model model, HttpSession session) {
        //是否跳转404
        Post post = postService.getPostByIdAndStatus(postId,1);
        if(post == null) {
            return "/Home/Error/404";
        }
        post.setUser(userService.getUserById(postService.getPostByPostId(postId).getPostUserId()));
        //浏览量增加
        post.setPostViewCount(post.getPostViewCount()+1);
        postService.updatePostView(post);
        //分页
        PageHelper.startPage(page,pageSize);
        ///评论
        List<Comment> comments = commentService.listCommentByPostId(postId);
        for(Comment comment : comments) {
            if(comment.getCommentPid() != null && comment.getCommentPid()>0) {
                Comment pComment = commentService.getCommentByCommentId(comment.getCommentPid());
                pComment.setCommentAuthorName(userService.getUserById(pComment.getCommentUserId()).getNickname());
                comment.setParentComment(pComment);
            }
        }
        PageInfo<Comment> pageInfo = new PageInfo<Comment>(comments);
        model.addAttribute("pageInfo", pageInfo);
        //热门帖子
        addHotPosts(model, 10);
        //最新帖子
        addRecentPosts(model, 10);
        //提供分页支持
        model.addAttribute("pageUrlPrefix", "/post/"+ postId +"?page");
        //注入页面基础数据元素
        model.addAttribute("userOperations",pageOptionsService.getAllUserOperations());
        model.addAttribute("pageOptions", pageOptionsService.getPageOperation());
        model.addAttribute("categoryList", categoryService.getAllCategories());
        model.addAttribute("post",post);
        model.addAttribute("category",categoryService.getCategoryById(post.getCategoryId()));
        if(session.getAttribute("like")==null) {
            session.setAttribute("like",false);
        }
        return "Home/Page/page";
    }

    /**
     * 点赞增加
     *
     * @param id 文章ID
     * @return 点赞量数量
     */
    @RequestMapping(value = "/like/{id}", method = {RequestMethod.POST}, produces = {"text/plain;charset=UTF-8"})
    @ResponseBody
    public String increaseLikeCount(@PathVariable("id") Integer id, HttpSession session) {
        Post post = postService.getPostByIdAndStatus(id, 1);
        Integer postCount = post.getLikeCount() + 1;
        post.setLikeCount(postCount);
        postService.updatePostLike(post);
        session.setAttribute("like",true);
        return null;
    }

    private void addRecentPosts(Model model, int num) {
        List<Post> recentPosts = postService.listRecentPost(10);
        model.addAttribute("recentPostList", recentPosts);
    }

    private void addHotPosts(Model model, int num) {
        List<Post> hotPosts = postService.listPostByViewCount(10);
        model.addAttribute("hotPostList", hotPosts);
    }

    @RequestMapping(value = "/backPostList")
    public String userBackPostList(@RequestParam(required = false, defaultValue = "1") Integer pageIndex,
                                   @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                   @RequestParam(required = false) String status, Model model,
                                   HttpSession session) {
        if (status == null) {
            model.addAttribute("pageUrlPrefix", "/post/backPostList?pageIndex");
        } else {
            model.addAttribute("pageUrlPrefix", "/post/backPostList?status=" + status + "&pageIndex");
        }

        User user = (User) session.getAttribute("user");
        PageInfo<Post> postPageInfo = postService.pagePost(pageIndex, pageSize, user);
        model.addAttribute("pageInfo", postPageInfo);
        return "Admin/Post/index";
    }

    @RequestMapping(value = "/noticeList")
    public ModelAndView noticeList() {
        ModelAndView modelandview = new ModelAndView();

        List<Post> noticeList = postService.getAllNotices();

        modelandview.addObject("noticeList", noticeList);

        modelandview.setViewName("Admin/Notice/index");
        return modelandview;
    }

    @RequestMapping(value = "/allPosts")
    public String allPosts(@RequestParam(required = false, defaultValue = "1") Integer pageIndex,
                           @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                           @RequestParam(required = false) String status, Model model,
                           HttpSession session) {
        if (status == null) {
            model.addAttribute("pageUrlPrefix", "/post/allPosts?pageIndex");
        } else {
            model.addAttribute("pageUrlPrefix", "/post/allPosts?status=" + status + "&pageIndex");
        }
        PageInfo<Post> postPageInfo = postService.pagePostAll(pageIndex, pageSize);
        model.addAttribute("pageInfo", postPageInfo);
        return "Admin/Post/allPost";
    }

    @RequestMapping("/insertPostView")
    public String insertPostView(Model model) {
        List<Category> categoryList = categoryService.getAllCategories();
        model.addAttribute("categoryList", categoryList);
        return "Admin/Post/edit";
    }

    @RequestMapping("/insertNoticeView")
    public String insertNoticeView(Model model) {
        Category category = categoryService.getNotice();
        model.addAttribute("category", category);
        return "Admin/Notice/insertNotice";
    }

    @RequestMapping(value = "/insertPost", method = RequestMethod.POST)
    public String insertPost(HttpSession session, Post newPost) {
        Post post = new Post();
        User user = (User) session.getAttribute("user");
        post.setPostUserId(user.getUserId());
        post.setTitle(newPost.getTitle());
        int summaryLength = 150;
        String summaryText = HtmlUtil.cleanHtmlTag(newPost.getPostContent());
        if (summaryText.length() > summaryLength) {
            String summary = summaryText.substring(0, summaryLength);
            post.setPostSummary(summary);
        } else {
            post.setPostSummary(summaryText);
        }
        post.setPostContent(newPost.getPostContent());
        post.setCategoryId(newPost.getCategoryId());
        Date date = new Date();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 日期格式化
//        date = sdf.parse(String.valueOf(date));
        post.setCreateTime(date);
        post.setUpdateTime(date);
        postService.insertPost(post);
        return "redirect:/post/backPostList";
    }

    @RequestMapping(value = "/insertNotice", method = RequestMethod.POST)
    public String insertNotice(HttpSession session, Post newPost) {
        Post post = new Post();
        User user = (User) session.getAttribute("user");
        post.setPostUserId(user.getUserId());
        post.setTitle(newPost.getTitle());
        int summaryLength = 150;
        String summaryText = HtmlUtil.cleanHtmlTag(newPost.getPostContent());
        if (summaryText.length() > summaryLength) {
            String summary = summaryText.substring(0, summaryLength);
            post.setPostSummary(summary);
        } else {
            post.setPostSummary(summaryText);
        }
        post.setPostContent(newPost.getPostContent());
        post.setCategoryId(newPost.getCategoryId());
        Date date = new Date();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 日期格式化
//        date = sdf.parse(String.valueOf(date));
        post.setCreateTime(date);
        post.setUpdateTime(date);
        postService.insertPost(post);
        return "redirect:/post/noticeList";
    }

    @RequestMapping(value = "/deletePost/{id}")
    public String deletePost(@PathVariable("id") Integer id, HttpSession session) {
        Post post = postService.getPostByIdAndStatus(id, 1);
        if (post == null) {
            return "redirect:/post/backPostList";
        }
        User user = (User) session.getAttribute("user");
        if (!Objects.equals(post.getPostUserId(), user.getUserId()) && user.getState() != 1) {
            return "redirect:/post/backPostList";
        }
        postService.deletePostById(id);
        commentService.deleteCommentByPostId(id);
        return "redirect:/post/backPostList";
    }

    @RequestMapping(value = "/deleteNotice/{id}")
    public String deleteNotice(@PathVariable("id") Integer id, HttpSession session) {
        postService.deletePostById(id);
        commentService.deleteCommentByPostId(id);
        return "redirect:/post/noticeList";
    }

    @RequestMapping(value = "/managerDeletePost/{id}")
    public String managerDeletePost(@PathVariable("id") Integer id, HttpSession session) {
        postService.deletePostById(id);
        commentService.deleteCommentByPostId(id);
        return "redirect:/post/allPosts";
    }

    @RequestMapping(value = "/recovery/{id}")
    public String recoveryPost(@PathVariable("id") Integer id, HttpSession session) {
        postService.recoveryPostById(id);
        commentService.recoveryCommentByPostId(id);
        return "redirect:/post/noticeList";
    }

    @RequestMapping(value = "/managerRecovery/{id}")
    public String managerRecoveryPost(@PathVariable("id") Integer id, HttpSession session) {
        postService.recoveryPostById(id);
        commentService.recoveryCommentByPostId(id);
        return "redirect:/post/allPosts";
    }

    @RequestMapping(value = "/updatePostView")
    public String updatePostView(@PathVariable("id") Integer id, Model model, HttpSession session) {
        Post post = postService.getPostByIdAndStatus(id, 1);
        if (post == null) {
            return "redirect:/404";
        }
        // 如果不是管理员，访问其他用户的数据，则跳转403
        User user = (User) session.getAttribute("user");
        if (!Objects.equals(post.getPostUserId(), user.getUserId()) && user.getState() != 1) {
            return "redirect:/403";
        }

        model.addAttribute("post", post);
        return "updatePostView";
    }

    @RequestMapping(value = "/updatePost", method = RequestMethod.POST)
    public String updatePost(Post newPost, HttpSession session) throws ParseException {
        Post post = postService.getPostByIdAndStatus(newPost.getPostId(), 1);
        if (post == null) {
            return "redirect:/404";
        }
        // 如果不是管理员，访问其他用户的数据，则跳转403
        User user = (User) session.getAttribute("user");
        if (!Objects.equals(post.getPostUserId(), user.getUserId()) && user.getState() != 1) {
            return "redirect:/403";
        }
        post.setTitle(newPost.getTitle());
        post.setPostSummary(newPost.getPostSummary());
        post.setPostContent(newPost.getPostContent());
        post.setCategoryId(newPost.getCategoryId());
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 日期格式化
        date = sdf.parse(String.valueOf(date));
        post.setUpdateTime(date);
        postService.updatePost(post);
        return "redirect:/post/backPostList";
    }

    /**
     * 帖子详情页显示
     *
     * @param postId 帖子ID
     * @return modelAndView
     */
    @RequestMapping(value = "/post/{postId}")
    public String getPostDetailPage(@PathVariable("postId") Integer postId, Model model) {

        //文章信息，分类，标签，作者，评论
        Post post = postService.getPostByIdAndStatus(postId, 1);
        if (post == null) {
            return "Home/Error/404";
        }

        //用户信息
        User user = userService.getUserById(post.getPostUserId());
        post.setUser(user);

        //文章信息
        model.addAttribute("post", post);

        //评论列表
        List<Comment> commentList = commentService.listCommentByPostId(postId);
        model.addAttribute("commentList", commentList);

        //相关文章
        Integer categoryId = postService.getCategoryIdByPostId(postId);
        List<Post> similarPostList = postService.listPostByCategoryId(categoryId, 5);
        model.addAttribute("similarPostList", similarPostList);

        //猜你喜欢
        List<Post> mostViewPostList = postService.listPostByViewCount(5);
        model.addAttribute("mostViewPostList", mostViewPostList);

        //获取下一篇帖子
        Post afterPost = postService.getAfterPost(postId);
        model.addAttribute("afterPost", afterPost);

        //获取上一篇文章
        Post prePost = postService.getPrePost(postId);
        model.addAttribute("prePost", prePost);

        //获得随机文章
        List<Post> randomPostList = postService.listRandomPost(8);
        model.addAttribute("randomPostList", randomPostList);
        //获得热评文章
        List<Post> mostCommentPostList = postService.listPostByCommentCount(8);
        model.addAttribute("mostCommentPostList", mostCommentPostList);

        return "Home/Page/page";
    }

    @RequestMapping(value = "/postDetail/{postId}")
    public String postDetail(@RequestParam(value = "page", defaultValue = "1") int page,
                             @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
                             @PathVariable("postId") Integer postId, Model model, HttpSession session) {
        //分页
        PageHelper.startPage(page,pageSize);
        ///评论
        List<Comment> comments = commentService.listCommentByPostId(postId);
        for(Comment comment : comments) {
            if(comment.getCommentPid() != null && comment.getCommentPid()>0) {
                Comment pComment = commentService.getCommentByCommentId(comment.getCommentPid());
                pComment.setCommentAuthorName(userService.getUserById(pComment.getCommentUserId()).getNickname());
                comment.setParentComment(pComment);
            }
        }
        PageInfo<Comment> pageInfo = new PageInfo<Comment>(comments);
        model.addAttribute("pageInfo", pageInfo);
        //提供分页支持
        model.addAttribute("pageUrlPrefix", "/post/postDetail/"+ postId +"?pageIndex");
        return "Admin/Post/postDetail";
    }

    @RequestMapping(value = "/postDetail/delete/{id}")
    public String deleteComment(@PathVariable("id") Integer id, HttpSession session) {
        commentService.deleteCommentByCommentId(id);
        Integer postId = commentService.getPostIdByCommentId(id);
        return "redirect:/post/postDetail/" + postId;
    }

    /**
     * 点赞增加
     *
     * @param id 文章ID
     * @return 点赞量数量
     */
    @RequestMapping(value = "/post/like/{id}", method = {RequestMethod.POST}, produces = {"text/plain;charset=UTF-8"})
    @ResponseBody
    public String increaseLikeCount(@PathVariable("id") Integer id) {
        Post post = postService.getPostByIdAndStatus(id, 1);
        Integer postCount = post.getLikeCount() + 1;
        post.setLikeCount(postCount);
        postService.updatePostLike(post);
        return null;
    }

    /**
     * 文章访问量数增加
     *
     * @param id 文章ID
     * @return 访问量数量
     */
    @RequestMapping(value = "/post/view/{id}", method = {RequestMethod.POST}, produces = {"text/plain;charset=UTF-8"})
    @ResponseBody
    public String increaseViewCount(@PathVariable("id") Integer id) {
        Post post = postService.getPostByIdAndStatus(id, 1);
        Integer postCount = post.getPostViewCount() + 1;
        post.setPostViewCount(postCount);
        postService.updatePostView(post);

        return null;
    }

    @RequestMapping(value = "/search")
    public String search(@RequestParam(required = false, defaultValue = "1") Integer pageIndex,
                         @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                         @RequestParam(required = false) String status, Model model,
                         HttpSession session,
                         @Param("search") String search) {
        if (status == null) {
            model.addAttribute("pageUrlPrefix", "/post/search?pageIndex");
        } else {
            model.addAttribute("pageUrlPrefix", "/post/search?status=" + status + "&pageIndex");
        }
        User user = (User) session.getAttribute("user");
        PageInfo<Post> postPageInfo = postService.pageSearchPost(pageIndex, pageSize, user, search);
        model.addAttribute("pageInfo", postPageInfo);
        return "Admin/Post/index";
    }

    @RequestMapping(value = "/allPostsSearch")
    public String allPostsSearch(@RequestParam(required = false, defaultValue = "1") Integer pageIndex,
                                 @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                 @RequestParam(required = false) String status, Model model,
                                 HttpSession session,
                                 @Param("search") String search,
                                 @Param("SearchType") String searchType) {
        if (status == null) {
            model.addAttribute("pageUrlPrefix", "/post/allPostsSearch?pageIndex");
        } else {
            model.addAttribute("pageUrlPrefix", "/post/allPostsSearch?status=" + status + "&pageIndex");
        }
        PageInfo<Post> postPageInfo = postService.pageSearchAllPost(pageIndex, pageSize, search, searchType);
        model.addAttribute("pageInfo", postPageInfo);
        return "Admin/Post/allPost";
    }
}
